package com.xinchao.job.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xinchao.common.constant.BusinessConstant;
import com.xinchao.common.constant.CmccApiConstant;
import com.xinchao.common.constant.DateFormatConstant;
import com.xinchao.common.dto.CityCmccInfoDTO;
import com.xinchao.common.dto.DeviceSimInfoTrafficDTO;
import com.xinchao.common.util.CmccApiUtils;
import com.xinchao.common.util.DateUtils;
import com.xinchao.job.service.CityCmccInfoService;
import com.xinchao.job.service.DeviceSimInfoService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 更新终端sim卡信息历史总流量
 *
 * @author dxy
 * @date 2018/9/10 16:57
 */
@DisallowConcurrentExecution
public class SimHistoryTrafficJob extends QuartzJobBean {
	private static Logger logger = LoggerFactory.getLogger(SimHistoryTrafficJob.class);
	@Autowired
	private DeviceSimInfoService deviceSimInfoService;
	@Autowired
	private CityCmccInfoService cityCmccInfoService;

	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		//4.2.2.4	单个号码历史月流量查询
		String method = "triopi.member.monthflow.realtime.query";
		try {
			//城市对应的集团编码，应用键对应值，密钥的MAP
			Map<String, CityCmccInfoDTO> cityCmccInfoMap = cityCmccInfoService.getCityCmccInfoMap();
 			if (cityCmccInfoMap != null && cityCmccInfoMap.size() > 0) {
				Set<String> citySet = cityCmccInfoMap.keySet();
				for (String city : citySet) {
					//获取城市对应的集团编码，应用键对应值，密钥
					CityCmccInfoDTO cityCmccInfoDTO = cityCmccInfoMap.get(city);
					String appKeyValue = cityCmccInfoDTO.getAppKey();
					String secrect = cityCmccInfoDTO.getSecrect();
					String groupCode = cityCmccInfoDTO.getGroupCode();
					//获取终端sim卡信息总数
					Long count = deviceSimInfoService.countDeviceSimInfo(city);
					if (count != null && count > 0) {
						//获取近期六个月的月份数据，数据格式为yyyyMM
						long currentTimeMillis = System.currentTimeMillis();
						String yearMonth = DateUtils.longTimeStampToStringDate(currentTimeMillis, DateFormatConstant.DATE_YEAR_MONTH);
						//获取年
						String year = yearMonth.substring(0, 4);
						int intYear = Integer.parseInt(year);
						//获取月
						String month = yearMonth.substring(4, yearMonth.length());
						int intMonth = Integer.parseInt(month);
						String[] nearSixMonth = DateUtils.getNearSixMonth(intYear, intMonth);
//						logger.info("nearSixMonth:" + nearSixMonth);
						//获取上一个月月份
						String lastDateOfMonth = DateUtils.getLastDateOfMonth(intYear, intMonth, DateFormatConstant.DATE_YEAR_MONTH);
						//默认条数
						List<DeviceSimInfoTrafficDTO> trafficList = deviceSimInfoService.listDeviceSimInfoTraffic(city);
						if (CollectionUtils.isNotEmpty(trafficList)) {
							for (int j = 0; j < trafficList.size(); j++) {
								DeviceSimInfoTrafficDTO trafficDTO = trafficList.get(j);
								// iccid
								String iccid = trafficDTO.getIccid();
								if (StringUtils.isBlank(iccid)) {
									continue;
								}
								// 历史总流量
								String historicalTotalTraffic = trafficDTO.getHistoricalTotalTraffic();
								// 如果历史总流量为空，就查询近期六个月的流量数据（因为移动提供的接口，只能查询近期六个月的流量）
								if (StringUtils.isBlank(historicalTotalTraffic)) {
									double tempFlow = 0.0;
									for (int k = 0; k < nearSixMonth.length; k++) {
										// TODO 单次调用接口查询多条数据，@see
										// ERROR com.xinchao.job.task.SimHistoryTrafficJob - DeviceSimInfoSchedule updateDeviceSimInfoHistoryTraffic 更新终端sim卡信息历史总流量：应用调用服务的频率超限:请降低服务访问的频率[isv.invalid-invoketimes-group:xxx->频繁调用次数200/分钟;]
										String str = CmccApiUtils.bachQuery(method, iccid, false, nearSixMonth[k], appKeyValue, secrect, groupCode);
										double flow = parseDailyFlow(str);
										tempFlow = tempFlow + flow;
									}
									trafficDTO.setHistoricalTotalTraffic(tempFlow + BusinessConstant.DATA_UNIT_M);
//									deviceSimInfoService.updateDeviceSimInfoHistoryTraffic(trafficDTO);
								} else {
									// 如果不为空，就查询上一个月的流量+以前的总流量
									double historicalFlow = Double.parseDouble(
											historicalTotalTraffic.replaceAll(BusinessConstant.DATA_UNIT_M, ""));
									String resultStr = CmccApiUtils.bachQuery(method, iccid, false, lastDateOfMonth,appKeyValue, secrect, groupCode);
//									logger.info(">> updateDeviceSimInfoHistoryTraffic.CmccApiUtils.bachQuery: " + resultStr);
									double flow = parseDailyFlow(resultStr);
									historicalFlow = historicalFlow + flow;
									trafficDTO.setHistoricalTotalTraffic(historicalFlow + BusinessConstant.DATA_UNIT_M);
//									deviceSimInfoService.updateDeviceSimInfoHistoryTraffic(trafficDTO);
								}
							}
							//批量更新
//							logger.info("updateDeviceSimInfoHistoryTraffic-trafficList: " + JSON.toJSONString(trafficList));
							deviceSimInfoService.updateDeviceSimInfoHistoryTrafficBatch(trafficList);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceSimInfoSchedule updateDeviceSimInfoHistoryTraffic 更新终端sim卡信息历史总流量：" + e.getMessage());
		}
	}


	/**
	 * 解析单个号码历史月流量
	 *
	 * @param jsonStr JSON格式字符串
	 * @return double(历史月流量 ）
	 */
	private double parseDailyFlow(String jsonStr) {
		if (StringUtils.isBlank(jsonStr)) {
			throw new NullPointerException("输入JSON格式字符串不能为空");
		}
		JSONObject jsonObject = JSON.parseObject(jsonStr);
		JSONArray apnInfoJsonArray = jsonObject.getJSONArray(CmccApiConstant.JSON_KEY_APN_INFO);
		double usedFlow = 0.0;
		if (apnInfoJsonArray != null && apnInfoJsonArray.size() > 0) {
			for (int k = 0; k < apnInfoJsonArray.size(); k++) {
				JSONObject apnJsonObj = apnInfoJsonArray.getJSONObject(k);
				if (apnJsonObj != null) {
					JSONObject monthlyJsonObj = apnJsonObj.getJSONObject(CmccApiConstant.JSON_KEY_MONTHLY_LIST);
					if (monthlyJsonObj != null) {
						JSONArray listJsonArray = monthlyJsonObj.getJSONArray(CmccApiConstant.JSON_KEY_LIST);
						if (listJsonArray != null && listJsonArray.size() > 0) {
							for (int m = 0; m < listJsonArray.size(); m++) {
								JSONObject jsonObj = listJsonArray.getJSONObject(m);
								usedFlow = jsonObj.getDoubleValue(CmccApiConstant.JSON_KEY_USED_FLOW);
							}
						}
					}
				}
			}
		}
		return usedFlow;
	}
}
